package com.tencent.wxcloudrun.controller;

import com.tencent.wxcloudrun.config.ApiResponse;
import com.tencent.wxcloudrun.dto.PaginationInfo;
import com.tencent.wxcloudrun.model.Task;
import com.tencent.wxcloudrun.model.User;
import com.tencent.wxcloudrun.service.TaskService;
import com.tencent.wxcloudrun.service.UserService;
import com.tencent.wxcloudrun.utils.JwtUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Optional;

@RestController
@RequestMapping("/tasks")
public class TaskController {

    @Resource
    private TaskService taskService;

    @Resource
    private UserService userService;




    /**
     * 查询任务列表，支持分页和任务状态、逾期日期等条件
     */
    @GetMapping("/list")
    public ApiResponse getTaskList(
            @RequestHeader("Authorization") String token,
            @RequestParam(required = false) Task.TaskStatus status,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate dateTime,
            @RequestParam(required = false) String name,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        if (token == null || token.isEmpty()) {
            return ApiResponse.authError("未登录");
        }
        String mobile = JwtUtil.parseToken(token);
        if (mobile == null) {
            return ApiResponse.authError("登录已过期，请重新登录");
        }
        Optional<User> user = userService.findByMobile(mobile);
        if (!user.isPresent()) {
            return ApiResponse.authError("用户不存在");
        }
        Pageable pageable = PageRequest.of(page, size);
        Page<Task> result = taskService.searchTaskRecords(user.get().getId(), status, phone, name, dateTime, pageable);

        // 转换为新的数据结构
        PaginationInfo<Task> paginationInfo = new PaginationInfo<>(
                result.getContent(),
                result.getTotalElements(), // 总记录数
                result.getNumber() + 1, // 当前页码（前端页码从 1 开始）
                result.getSize() // 每页数量
        );
        return ApiResponse.ok(paginationInfo);
    }
}
